//
//  HJVideoControllView.m
//  project
//
//  Created by yefei on 2019/7/20.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJVideoControllView.h"
#import "GKLikeView.h"
#import "YFJourneyModel.h"
#import "HJViewModel.h"

@implementation HJVideoItemButton

- (void)layoutSubviews {
    [super layoutSubviews];
    
    [self.imageView sizeToFit];
    [self.titleLabel sizeToFit];
    
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;
    
    CGFloat imgW = self.imageView.frame.size.width;
    CGFloat imgH = self.imageView.frame.size.height;
    
    self.imageView.frame = CGRectMake((width - imgH) / 2, 0, imgW, imgH);
    
    CGFloat titleW = self.titleLabel.frame.size.width;
    CGFloat titleH = self.titleLabel.frame.size.height;
    
    self.titleLabel.frame = CGRectMake((width - titleW) / 2, height, titleW, titleH);
}

@end


@interface HJVideoControllView ()

/**
 头像
 */
@property (nonatomic, strong) UIImageView *avatorImageView;

/**
 点赞
 */
@property (nonatomic, strong) GKLikeView *likeView;


/**
 暂停按钮
 */
@property (nonatomic, strong) UIButton *playBtn;

/**
 分享
 */
@property (nonatomic, strong) HJVideoItemButton *shareBtn;

/**
 名字
 */
@property (nonatomic, strong) UILabel *nameLabel;

/**
 内容
 */
@property (nonatomic, strong) UILabel *contentLabel;

/**
 关注按钮
 */
@property (nonatomic, strong) UIButton * guanzhuBtn;



@end
// 适配比例
#define ADAPTATIONRATIO     SCREEN_WIDTH / 750.0f

@implementation HJVideoControllView

-(instancetype)init {
    if (self =[super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UpdateCommentNoti:) name:NotificationCommentCount object:nil];
        [self addSubview:self.coverImgView];
        [self addSubview:self.avatorImageView];
        [self addSubview:self.guanzhuBtn];
        [self addSubview:self.likeView];
        [self addSubview:self.commentBtn];
        [self addSubview:self.shareBtn];
        [self addSubview:self.nameLabel];
        [self addSubview:self.contentLabel];
        [self addSubview:self.sliderView];
        [self addSubview:self.playBtn];
         @weakify(self)
        [self.coverImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.edges.equalTo(self);
        }];
        
        [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.left.equalTo(self).offset(ADAPTATIONRATIO * 30.0f);
            make.bottom.equalTo(self).offset(-(ADAPTATIONRATIO * 30.0f));
            make.width.mas_equalTo(ADAPTATIONRATIO * 504.0f);
        }];
        
        [self.sliderView mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.top.equalTo(self.contentLabel.mas_bottom).offset(5);
            make.left.right.equalTo(self);
            make.height.mas_equalTo(ADAPTATIONRATIO * 1.0f);
        }];
        
        [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.left.equalTo(self.contentLabel);
            make.bottom.equalTo(self.contentLabel.mas_top).offset(-ADAPTATIONRATIO * 20.0f);
        }];
        
        [self.shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.right.equalTo(self).offset(-ADAPTATIONRATIO * 30.0f);
            make.bottom.equalTo(self.sliderView.mas_top).offset(-ADAPTATIONRATIO * 100.0f);
            make.width.height.mas_equalTo(ADAPTATIONRATIO * 110.0f);
        }];
        
        [self.commentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.centerX.equalTo(self.shareBtn);
            make.bottom.equalTo(self.shareBtn.mas_top).offset(-ADAPTATIONRATIO * 45.0f);
            make.width.height.mas_equalTo(ADAPTATIONRATIO * 110.0f);
        }];
        
        [self.likeView mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.centerX.equalTo(self.shareBtn);
            make.bottom.equalTo(self.commentBtn.mas_top).offset(-ADAPTATIONRATIO * 45.0f);
            make.width.height.mas_equalTo(ADAPTATIONRATIO * 110.0f);
        }];
        
        [self.avatorImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.centerX.equalTo(self.shareBtn);
            make.bottom.equalTo(self.likeView.mas_top).offset(-ADAPTATIONRATIO * 70.0f);
            make.width.height.mas_equalTo(ADAPTATIONRATIO * 110.0f);
            [self.avatorImageView rounded:UIRectCornerAllCorners radius:((ADAPTATIONRATIO * 110.0f)/2)];
        }];
        
        [self.guanzhuBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.centerX.equalTo(self.avatorImageView);
            make.bottom.equalTo(self.avatorImageView.mas_bottom).offset(15);
            make.size.mas_equalTo(CGSizeMake(30, 30));
        }];
        
        [self.playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.center.equalTo(self);
            make.size.mas_equalTo(CGSizeMake(70, 70));
        }];
    }
    return self;
}

#pragma mark - Public Methods
- (void)setProgress:(float)progress {
    self.sliderView.value = progress;
}

- (void)startLoading {
    [self.sliderView showLineLoading];
}

- (void)stopLoading {
    [self.sliderView hideLineLoading];
}
- (void)showPlayBtn {
    self.playBtn.hidden = NO;
}

- (void)hidePlayBtn {
    self.playBtn.hidden = YES;
}
- (void)showLikeAnimation {
    [self.likeView startAnimationWithIsLike:YES];
}

- (void)showUnLikeAnimation {
    [self.likeView startAnimationWithIsLike:NO];
}

#pragma mark - Action
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    NSTimeInterval delayTime = 0.3f;
    if (touch.tapCount <= 1) {
        [self performSelector:@selector(controlViewDidClick) withObject:nil afterDelay:delayTime];
    }else {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(controlViewDidClick) object:nil];
        if ([self.delegate respondsToSelector:@selector(controlView:touchesBegan:withEvent:)]) {
            [self.delegate controlView:self touchesBegan:touches withEvent:event];
        }
    }
}
- (void)controlViewDidClick {
    if ([self.delegate respondsToSelector:@selector(controlViewDidClickSelf:)]) {
        [self.delegate controlViewDidClickSelf:self];
    }
}

- (void)iconDidClick:(id)sender {
    if ([self.delegate respondsToSelector:@selector(controlViewDidClickIcon:)]) {
        [self.delegate controlViewDidClickIcon:self];
    }
}

#pragma mark - 懒加载
- (UIImageView *)coverImgView {
    if (!_coverImgView) {
        _coverImgView = [UIImageView new];
        _coverImgView.contentMode = UIViewContentModeScaleAspectFit;
        _coverImgView.clipsToBounds = YES;
    }
    return _coverImgView;
}

-(UIImageView *)avatorImageView {
    if (!_avatorImageView) {
        _avatorImageView = [UIImageView new];
        _avatorImageView.contentMode = UIViewContentModeScaleToFill;
        _avatorImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *iconTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(iconDidClick:)];
        [_avatorImageView addGestureRecognizer:iconTap];
    }
    return _avatorImageView;
}
-(HJViewModel *)viewModel {
    return [HJViewModel new];
}

-(UIButton *)guanzhuBtn {
    if (!_guanzhuBtn) {
        _guanzhuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_guanzhuBtn setImage:[UIImage imageNamed:@"guanzhu"] forState:0];
        @weakify(self)
        [[_guanzhuBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [[self viewModel] loadConcernDataWithParams:@{@"userId":self->_model.user.userId} success:^{
                @weakify(self)
                dispatch_async(dispatch_get_main_queue(), ^{
                    @strongify(self)
                    self.guanzhuBtn.hidden = YES;
                    if ([self.delegate respondsToSelector:@selector(controlViewDidClickAttention:videoModel:)]) {
                        [self.delegate controlViewDidClickAttention:self videoModel:self->_model];
                    }
                });
            } failure:^(NSString * _Nonnull error) {
                [YFHud showError:error];
            }];
        }];
    }
    return _guanzhuBtn;
}
- (GKLikeView *)likeView {
    if (!_likeView) {
        _likeView = [GKLikeView new];
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]init];
        @weakify(self)
        [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            @strongify(self)
            [self likeBtnClicked];
        }];
        [_likeView addGestureRecognizer:tap];
    }
    return _likeView;
}
//-(HJCommentView *)commentView {
//    if (!_commentView) {
//        _commentView = [[HJCommentView alloc]init];
//        [_commentView loadDataWorkWithModel:self->_model];
//        @weakify(self)
//        _commentView.close = ^{
//            @strongify(self)
//            [self hideCommentView];
//        };
//        [[UIApplication sharedApplication].keyWindow addSubview:_commentView];
//    }
//    return _commentView;
//}
//
//-(void)showCommentView {
//    [UIView animateWithDuration:0.3 animations:^{
//        self.commentView.frame = CGRectMake(0, SCREEN_HEIGTH/5*2, SCREEN_WIDTH, SCREEN_HEIGTH/5*3);
//    }];
//}
//-(void)hideCommentView {
//    [UIView animateWithDuration:0.3 animations:^{
//        self.commentView.frame = CGRectMake(0, SCREEN_HEIGTH, SCREEN_WIDTH, SCREEN_HEIGTH/5*3);
//    } completion:^(BOOL finished) {
//        [self.commentView removeFromSuperview];
//    }];
//}
- (HJVideoItemButton *)commentBtn {
    if (!_commentBtn) {
        _commentBtn = [HJVideoItemButton new];
        [_commentBtn setImage:[UIImage imageNamed:@"pinglun"] forState:UIControlStateNormal];
        _commentBtn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
        [_commentBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        @weakify(self)
        [[_commentBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            if ([self.delegate respondsToSelector:@selector(controlViewDidClickComment:)]) {
                [self.delegate controlViewDidClickComment:self];
            }
        }];
    }
    return _commentBtn;
}

- (HJVideoItemButton *)shareBtn {
    if (!_shareBtn) {
        _shareBtn = [HJVideoItemButton new];
        [_shareBtn setImage:[UIImage imageNamed:@"fenxiang"] forState:UIControlStateNormal];
        _shareBtn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
        [_shareBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        @weakify(self)
        [[_shareBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            if ([self.delegate respondsToSelector:@selector(controlViewDidClickShare:)]) {
                [self.delegate controlViewDidClickShare:self];
            }
        }];
    }
    return _shareBtn;
}

- (UILabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [UILabel new];
        _nameLabel.textColor = [UIColor whiteColor];
        _nameLabel.font = [UIFont boldSystemFontOfSize:15.0f];
        _nameLabel.userInteractionEnabled = YES;
    }
    return _nameLabel;
}

- (UILabel *)contentLabel {
    if (!_contentLabel) {
        _contentLabel = [UILabel new];
        _contentLabel.numberOfLines = 0;
        _contentLabel.textColor = [UIColor whiteColor];
        _contentLabel.font = [UIFont systemFontOfSize:14.0f];
    }
    return _contentLabel;
}

- (GKSliderView *)sliderView {
    if (!_sliderView) {
        _sliderView = [GKSliderView new];
        _sliderView.isHideSliderBlock = YES;
        _sliderView.sliderHeight = ADAPTATIONRATIO * 1.0f;
        _sliderView.maximumTrackTintColor = [UIColor clearColor];
        _sliderView.minimumTrackTintColor = [UIColor whiteColor];
    }
    return _sliderView;
}

/**
 暂停按钮
 @return pasueBtn
 */
-(UIButton *)playBtn {
    if (!_playBtn) {
        _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playBtn setImage:setImage(@"pauseBtn") forState:0];
        _playBtn.adjustsImageWhenHighlighted = YES;
        [_playBtn rounded:UIRectCornerAllCorners radius:35];
//        [_playBtn setBackgroundColor:[UIColor colorWithHex:0x39C5BB]];
        _playBtn.hidden = YES;
    }
    return _playBtn;
}
#pragma mark --点赞
-(void)likeBtnClicked {
    self.likeView.userInteractionEnabled = NO;
    int zannum = _model.praiseAmount.intValue;
    BOOL isPraise = [_model.isPraise boolValue];
    if (isPraise) {
        zannum--;
    }else {
        zannum++;
    }
    isPraise = !isPraise;
    _model.praiseAmount = [NSString stringWithFormat:@"%d",zannum];
    @weakify(self)
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"albumId"] = _model.albumId;
    [[self viewModel] loadPraiseDataWorkWithParams:params Success:^{
        @strongify(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.likeView setupLikeState:isPraise];
            [self.likeView setupLikeCount:[NSString stringWithFormat:@"%d",zannum]];
            self.likeView.userInteractionEnabled = YES;
            if (isPraise) {
                self->_model.isPraise = @"1";
            }else {
                self->_model.isPraise = @"0";
            }
        });
    } failure:^(NSString * _Nonnull error) {
        [YFHud showError:error];
    }];
}

//关注按钮显示与隐藏
- (void)setConcern:(BOOL)concern {
    self.guanzhuBtn.hidden = concern;
}


#pragma mark --  赋值
-(void)setModel:(HJVideoModel *)model {
    _model = model;
    [self.coverImgView sd_setImageWithURL:[NSURL URLWithString:model.videoSource.thumbnail] placeholderImage:nil];
    [self.avatorImageView sd_setImageWithURL:[NSURL URLWithString:model.user.avatar]];
    self.contentLabel.text = model.content;
    self.nameLabel.text = model.user.nickName;
    [self.shareBtn setTitle:@"分享" forState:0];
    self.guanzhuBtn.hidden = model.concern;
    [self.commentBtn setTitle:model.reviewAmount forState:0];
    [self.likeView setupLikeState:[model.isPraise boolValue]];
    [self.likeView setupLikeCount:model.praiseAmount];
}

/**
 更新评论数
 return 评论数通知
 */
-(void)UpdateCommentNoti:(NSNotification *)noti {
    int count = _model.reviewAmount.intValue;
    [self.commentBtn setTitle:[NSString stringWithFormat:@"%d",count] forState:0];
}

@end
